package com.bjy.qa.util;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 机器人消息工具类
 */
@Component
public class RobotMsgTool {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RestTemplate restTemplate;

    @Value("${qa-platform.robot.client.host}")
    private String clientHost; // 前端部署的 host

    @Value("${qa-platform.robot.img.success}")
    private String successUrl; // 成功时的图片url
    @Value("${qa-platform.robot.img.warning}")
    private String warningUrl; // 警告时的图片url
    @Value("${qa-platform.robot.img.skip}")
    private String skipUrl; // 中断时的图片url
    @Value("${qa-platform.robot.img.error}")
    private String errorUrl; // 失败时的图片url

    /**
     * 签名并发送通知
     * @param token 机器人token
     * @param secret 机器人密钥
     * @param type 机器人类型
     * @param jsonObject 通知内容
     */
    private void signAndSend(String token, String secret, int type, JSONObject jsonObject) {
        clientHost = clientHost.replace(":80/", "/");
        try {
//            switch (type) {
//                case RobotType.DingTalk: {
                    String path = "";
                    if (!StringUtils.isEmpty(secret)) {
                        Long timestamp = System.currentTimeMillis();
                        String stringToSign = timestamp + "\n" + secret;
                        Mac mac = Mac.getInstance("HmacSHA256");
                        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
                        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
                        String sign = URLEncoder.encode(new String(Base64Utils.encode(signData)), "UTF-8");
                        path = "&timestamp=" + timestamp + "&sign=" + sign;
                    }

                    ResponseEntity<JSONObject> responseEntity =
                            restTemplate.postForEntity(token + path
                                    , jsonObject, JSONObject.class);
                    logger.info("robot result: " + responseEntity.getBody());
//                    break;
//                }
//                case RobotType.WeChat: {
//                    ResponseEntity<JSONObject> responseEntity =
//                            restTemplate.postForEntity(token, jsonObject, JSONObject.class);
//                    logger.info("robot result: " + responseEntity.getBody());
//                    break;
//                }
//                case RobotType.FeiShu: {
//                    if (!StringUtils.isEmpty(secret)) {
//                        String timestamp = String.valueOf(System.currentTimeMillis()).substring(0, 10);
//                        String stringToSign = timestamp + "\n" + secret;
//                        Mac mac = Mac.getInstance("HmacSHA256");
//                        mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
//                        byte[] signData = mac.doFinal(new byte[]{});
//                        String sign = new String(Base64Utils.encode(signData));
//                        jsonObject.put("timestamp", timestamp);
//                        jsonObject.put("sign", sign);
//                    }
//                    ResponseEntity<JSONObject> responseEntity =
//                            restTemplate.postForEntity(token, jsonObject, JSONObject.class);
//                    logger.info("robot result: " + responseEntity.getBody());
//                    break;
//                }
//                case RobotType.YouSpace: {
//                    JSONObject you = new JSONObject();
//                    you.put("timestamp", System.currentTimeMillis());
//                    you.put("content", Base64Utils.encode(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8)));
//                    ResponseEntity<JSONObject> responseEntity =
//                            restTemplate.postForEntity(token
//                                    , you, JSONObject.class);
//                    logger.info("robot result: " + responseEntity.getBody());
//                    break;
//                }
//            }
        } catch (Exception e) {
            logger.info("robot send failed, cause: " + e.getMessage());
        }
    }

    /**
     * 发送每次测试结果
     * @param token 机器人token
     * @param secret 机器人密钥
     * @param title 测试报告标题
     * @param suiteName 套件名称
     * @param pass 通过数量
     * @param warn 警告数量
     * @param fail 失败数量
     * @param linkUri 连接消息，对应打开的 URI 地址
     * @param type 机器人类型
     */
    public void sendResultFinishReport(String token, String secret, String title, String suiteName, int pass, int warn, int skip, int fail, String linkUri, int type) {
        JSONObject jsonObject = new JSONObject();
//        switch (type) {
//            case RobotType.DingTalk: {
                String img = ""; // 判断测试结果，来决定显示什么图片
                String icon = "";
                if (fail > 0) {
                    img = errorUrl;
                    icon = " ❌";
                } else if (skip > 0) {
                    img = skipUrl;
                    icon = " ⏸️";
                } else if (warn > 0) {
                    img = warningUrl;
                    icon = " ⚠️️";
                } else {
                    img = successUrl;
                    icon = " ✅ ";
                }

                String text = "### 统一测试平台 - " + title + icon + "\n" +
                        "#### 测试套件: " + suiteName + " 运行完毕！  \n  " +
                        "> - 通过：" + pass + "  \n  " +
                        "> - 异常：" + warn + "  \n  " +
                        "> - 暂停：" + skip + "  \n  " +
                        "> - 失败：" + fail+ "  \n  " +
                        "######  [查看报告详情](" + clientHost + linkUri + ")  \n  ";

                JSONObject markdown = new JSONObject();
                markdown.put("title", "统一测试平台 - " + title + " 测试套件: " + suiteName + " 运行完毕！");
                markdown.put("text", text);

                jsonObject = new JSONObject();
                jsonObject.put("msgtype", "markdown");
                jsonObject.put("markdown", markdown);
//                break;
//            }
//            case RobotType.WeChat: {
//                jsonObject.put("msgtype", "markdown");
//                JSONObject markdown = new JSONObject();
//                markdown.put("content", "**测试套件: " + suiteName + " 运行完毕！**\n" +
//                        "通过数：" + pass + " \n" +
//                        "异常数：" + warn + " \n" +
//                        "失败数：" + fail + "\n" +
//                        "测试报告：[点击查看](" + clientHost + "/Home/" + projectId + "/ResultDetail/" + resultId + ")");
//                jsonObject.put("markdown", markdown);
//                break;
//            }
//            case RobotType.FeiShu: {
//                jsonObject.put("msg_type", "interactive");
//                JSONObject card = new JSONObject();
//                JSONObject config = new JSONObject();
//                config.put("wide_screen_mode", true);
//                card.put("config", config);
//                JSONObject element = new JSONObject();
//                element.put("tag", "markdown");
//                List<JSONObject> elementList = new ArrayList<>();
//                element.put("content", "**测试套件: " + suiteName + " 运行完毕！**\n" +
//                        "通过数：" + pass + " \n" +
//                        "异常数：" + warn + " \n" +
//                        "失败数：" + fail + "\n" +
//                        "测试报告：[点击查看](" + clientHost + "/Home/" + projectId + "/ResultDetail/" + resultId + ")");
//                elementList.add(element);
//                card.put("elements", elementList);
//                jsonObject.put("card", card);
//                break;
//            }
//            case RobotType.YouSpace: {
//                jsonObject.put("businessId", "测试套件: " + suiteName + " 运行完毕！");
//                JSONObject titleZone = new JSONObject();
//                titleZone.put("type", 0);
//                titleZone.put("text", "测试套件: " + suiteName + " 运行完毕！");
//                jsonObject.put("titleZone", titleZone);
//                List<JSONObject> contentZone = new ArrayList<>();
//                contentZone.add(generateYouTextView("通过数：" + pass));
//                contentZone.add(generateYouTextView("异常数：" + warn));
//                contentZone.add(generateYouTextView("失败数：" + fail));
//                JSONObject button = new JSONObject();
//                button.put("type", "buttonView");
//                JSONObject data = new JSONObject();
//                data.put("mode", 0);
//                data.put("text", "点击查看测试报告");
//                data.put("url", "[" + clientHost + "/Home/" + projectId + "/ResultDetail/" + resultId + "](" + clientHost + "/Home/" + projectId + "/ResultDetail/" + resultId + ")");
//                button.put("data", data);
//                contentZone.add(button);
//                jsonObject.put("contentZone", contentZone);
//                break;
//            }
//        }
        signAndSend(token, secret, type, jsonObject);
    }
}
